//获取token
function getToken(){
	var localToken = localStorage.getItem('_token');
	if(localToken == null || localToken == ''){
		xget(
			wxUrl + '/v3.2/login/token',
			{},
			function(data){
				token = data.data.token;
				localStorage.setItem('_token',token);
			}
		);
	}else{
		token = localToken;
	}
}
//获取userToken
function getUserToken(){
	var localUserToken = localStorage.getItem('_userToken');
	if(localUserToken!= null && localUserToken != ''){
		userToken = localUserToken;
	}
}

//获取定位信息
function getLocation(){
	var location = localStorage.getItem('_location');
	var result = JSON.parse(location);
	if(result == null || result == ''){
		var geolocation = new BMap.Geolocation();
		geolocation.getCurrentPosition(function(r){
			if(this.getStatus()== BMAP_STATUS_SUCCESS){
				longitude = r.point.lng;
				latitude = r.point.lat;
				//根据经纬度获取省市县
				var point = new BMap.Point(longitude,latitude);
				var gc = new BMap.Geocoder();
				gc.getLocation(point, function(rs){
					var addComp = rs.addressComponents;
					province = addComp.province;
					city = addComp.city;
					district = addComp.district;
					//本地存储定位信息
					var locationData = new Object;
					locationData.province = province;
					locationData.city = city;
					locationData.district = district;
					locationData.longitude = longitude;
					locationData.latitude = latitude;
					var locationStr = JSON.stringify(locationData);
					localStorage.setItem('_location',locationStr);
					//首页定位显示当前市
					var cityName = document.getElementById('cityName');
					if(cityName){
						$("#cityName").text(city);
					}
				});
			}
		},{enableHighAccuracy: true});
	}else{
		province = result.province;
		city = result.city;
		district = result.district;
		longitude = result.longitude;
		latitude = result.latitude;
	}
}

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

// 根据url判断
setTimeout(function(){
	var url1 = window.location.href;
	if(url1.indexOf("sales_index")>0){
		$("footer .foot01").addClass("active01");
		$("footer .foot01").parent('p').addClass("redOn");
		$("footer .foot02").removeClass("active02");
		$("footer .foot03").removeClass("active03");
	}else if(url1.indexOf("buy_list.html")>0){
		$("footer .foot01").removeClass("active01");
		$("footer .foot02").addClass("active02");
		$("footer .foot02").parent('p').addClass("redOn");
		$("footer .foot03").removeClass("active03");
	}else if(url1.indexOf("farmManage")>0){
		$("footer .foot01").removeClass("active01");
		$("footer .foot02").removeClass("active02");
		$("footer .foot03").addClass("active03");
		$("footer .foot03").parent('p').addClass("redOn");
	}
},500);


//localStorage.clear();
// 添加全局拦截器
Vue.http.interceptors.push(function(request, next) {
	this.showLoading = true
	next(function(response){
		if(response.ok){
			var result = JSON.parse(response.body);
			if(0!=result.code){
				if(10200 == result.code || 10395 == result.code){
					this.$http.get(wxUrl + "/v3.2/login/login", {params:{token: token}})
					.then(function(response) {
						var result = JSON.parse(response.body);
						if(result){
				        	if(result.code == 0){
				        		if(result.data.success==true){
				        			if(result.data.register==true){
				        				localStorage.setItem("_userToken", result.data.userToken);
				        				location.reload();
				        			}else{//注册手机号
				        				window.location.href= self_base_path + "/userCenter/signIn.html";
				        			}
				        		}else{//微信授权
				        			var url = window.location;
				        			window.location.href= wxUrl + "/v3.2/login/auth?token=" + token + "&url=" + url;
				        		}
				        	}else{					        	
				        		promptBox(result.msg);
				        	}
				        }else{
				        	promptBox('网络异常！请检查您的网络！');
				        }
					});
				}else{
					if(10609 == result.code){
						promptBox('您需填写完善农庄信息');
						setTimeout(function(){
							window.location.href= self_base_path + "/userCenter/personalData.html";
						}, 1000);
					}
					if(10==result.code){
						localStorage.removeItem('_token');
						localStorage.removeItem('_userToken');
						getToken();
					}else{
						promptBox(result.msg);
					}
				}
			}
			this.showLoading = false
			return response
		} else {
			setTimeout(function(){
				$('.loading_modal').hide();
				promptBox('网络异常！');
			},6000);
		}
	});
});

// 全局过滤器 —— 100.00 > 100
Vue.filter("quzheng", function(value) {
	var numArray = value.split(".");
	var num1 = numArray[0];
	var num2 = numArray[1];
	if(num2 == 00){
		return value = num1;
	}else{
		return value;
	}
});

// 获取url中的参数
function getUrlParams() {
	var resultObj = {};
	var params = window.location.search.substr(1);
	if (params.length > 0 ) {
		var kvs = params.split("&");
		for (var str in kvs) {
			var j = kvs[str].split("=");
			resultObj[j[0]] = j[1];
		}
	}
	return resultObj;
}

//toast提示框
var toast_showing=false;
function promptBox(message){	
	if(toast_showing){return;}
	toast_showing=true;
	var newDiv = document.createElement("div");
	newDiv.setAttribute("id", "newD");
	newDiv.className="promptBox";
	newDiv.innerHTML=message;
	document.body.appendChild(newDiv);
	//shadow
	var shadowDiv = document.createElement("div");
	shadowDiv.setAttribute("id", "shadowId");
	shadowDiv.className="shadowClass";
	document.body.appendChild(shadowDiv);
	
	newDiv.style.display="block";
	setTimeout("removeDiv()", 1500);
	var clientWidth = document.body.clientWidth;
	var divWidth = $('#newD').width() + 30;
	var leftMuch = (clientWidth - divWidth)/2;
	$('#newD').css('left',leftMuch);
}
function removeDiv(){
	toast_showing=false;
	var promptDiv = document.getElementById('newD');
	document.body.removeChild(promptDiv);
	var shadowDiv = document.getElementById('shadowId');
	document.body.removeChild(shadowDiv);
}

//dialog确认框
function dialog(message,funA){
	var dialog = '<div class="modal" id="dialog">' +
							 '<div class="modal-content">' +
							 '<div class="modal-body"><p>'+message+'</P></div>' +
							 '<div class="modal-footer">' +
							 '<a id="cancel" class="btn-default">取消</a>' +
							 '<a id="confirm" class="btn-success">确定</a>' +
							 '</div>' +
							 '</div>' +
							 '</div>';
	jQuery("body").append(dialog);
	jQuery("#cancel").click(function(){
		jQuery("#dialog").remove();
	});
	jQuery("#confirm").click(function(){
		funA();
		jQuery("#dialog").remove();
	});
}

//jquery ajax get
function xget (url,param,callback,errorback){
	$.ajax({
		type:'get',
		url : url,
		data : param,
		success : callback,
		error : errorback
	});
}

// 验证登录——跳转页面
function vLoginJump(pageUrl){
	if(userToken != null && userToken != ''){
		var complete = localStorage.getItem('complete');
		if(complete){
			window.location.href= self_base_path + pageUrl;
		}else{
			vJump(pageUrl);
		}
	}else{
		vJump(pageUrl);
	}
}
function vJump(pageUrl){
	xget(
		wxUrl + "/v3.2/login/token",
		{token: token},
		function(data){
			if(data){
	    	if(data.code == 0){
	    		if(data.data.success==true){
	    			if(data.data.register==true){
	    				localStorage.setItem("_userToken", data.data.userToken);
							window.location.href= self_base_path + pageUrl;
	    			}else{ //绑定手机号
	    				window.location.href= self_base_path + "/userCenter/signIn.html";
	    			}
	    		}else{ //微信授权
	    			var url = window.location;
	    			window.location.href= wxUrl + "/v3.2/login/auth?token=" + token + "&url=" + url;
	    		}
	    	}else{
	    		promptBox(data.msg);
	    	}
	    }else{
	    	promptBox('网络异常，请检查您的网络！');
	    }
		}
	);
}

// 验证登录——收藏关注类
function vLoginClick(){
	if(userToken != null && userToken != ''){
		var complete = localStorage.getItem('complete');
		if(complete){
			return true;
		}else{
			vClick();
		}
	}else{
		vClick();
	}
}
function vClick(){
	xget(
		wxUrl + "/v3.2/login/login",
		{token: token},
		function(data){
			if(data){
	    	if(data.code == 0){
	    		if(data.data.success==true){
	    			if(data.data.register==true){
    					localStorage.setItem("_userToken", data.data.userToken);
    					return true;
	    			}else{ //绑定手机号
	    				window.location.href= self_base_path + "/userCenter/signIn.html";
	    			}
	    		}else{ //微信授权
	    			var url = window.location;
	    			window.location.href= wxUrl + "/v3.2/login/auth?token=" + token + "&url=" + url;
	    		}
	    	}else{
	    		promptBox(data.msg);
	    	}
	    }else{
	    	promptBox('网络异常，请检查您的网络！');
	    }
		}
	);
}

/**
	url表示地址
**/
function pushVHistory(backUrl){
	if(backUrl == false){
		return;
	}
	var vhistory;
	var item = sessionStorage.getItem("_syw_dz_wx_vhistory_");
	if(item == null || item=="" || item=="undefined"){
		vhistory = [self_base_path + '/sales/sales_index.html'];
	}else{
		vhistory = JSON.parse(item);
	}
	var url;
	if(backUrl==null || backUrl==''){
		url = window.location.href;
	}else{
		url = backUrl;
	}
	var lurl = vhistory.pop();
	if(url == lurl){
	}else{
		if(lurl != null)
			vhistory.push(lurl)
	}
	vhistory.push(url);
	console.log("push url："+ url);
	sessionStorage.setItem("_syw_dz_wx_vhistory_",JSON.stringify(vhistory));
	return;
}

/**
	-1表示历史记录后退一,go(-1);
	url表示地址
**/
function goBackVHistory(){
	var vhistory;
	var item = sessionStorage.getItem("_syw_dz_wx_vhistory_");
	if(item == null || item=="" || item=="undefined"){
		vhistory = [];
	}else{
		vhistory = JSON.parse(item);
	}
	/** 当前请求链接 **/
	var curl=window.location.href;
	
	var ctmp= window.location.pathname;
	
	var flag = true;
	var vhistoryUrl='';
	while(flag){
		vhistoryUrl=vhistory.pop();
		
		if(curl!=vhistoryUrl){
			flag = false;
		}
		if(flag == false && vhistoryUrl.split("?")[0].indexOf(ctmp)>0){
			flag = true;
		}
		if(vhistory.length<1){
			flag = false;
		}else{
			if(vhistoryUrl=='' || vhistoryUrl == null){
				flag = true;
			}
		}
	}
	sessionStorage.setItem("_syw_dz_wx_vhistory_",JSON.stringify(vhistory));
	if(vhistoryUrl!='' && vhistoryUrl != null){
		console.log("goBackVHistory url："+ vhistoryUrl);
		window.location.href=vhistoryUrl;
	}
	return;
}